package org.csource.pool;

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IntelliJ IDEA.
 * User: yangfei
 * Date: 2014/6/18
 * Time: 13:52
 * Desc: 对象池管理
 */

public class FastDfsObjectPool implements ObjectPool {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private static FastDfsObjectFactory fastDfsObjectFactory = new FastDfsObjectFactory(FastDfsImpl.getTracker_server(),FastDfsImpl.getHttpPort(),
            FastDfsImpl.getConnectTimeout(),FastDfsImpl.getNetworkTimeout(),FastDfsImpl.getToken(),FastDfsImpl.getCharset(),FastDfsImpl.getSecretKey());
    private static ObjectPool objectPool = null;
    private static GenericObjectPool.Config config = null;


    static {
            config = new GenericObjectPool.Config();
            config.maxActive = FastDfsImpl.getMaxActive();
            config.maxIdle = FastDfsImpl.getMinIdle() ;
            config.minIdle = FastDfsImpl.getMinIdle();
            objectPool = new GenericObjectPool(fastDfsObjectFactory,config);
    }

    @Override
    public Object borrowObject() throws Exception {
        return objectPool.borrowObject();
    }

    @Override
    public void returnObject(Object o) throws Exception {
        objectPool.returnObject(o);
    }

    @Override
    public void invalidateObject(Object o) throws Exception {
        objectPool.invalidateObject(o);
    }

    @Override
    public void addObject() throws Exception {
        objectPool.addObject();
    }

    @Override
    public int getNumIdle() throws UnsupportedOperationException {
        return objectPool.getNumIdle();
    }

    @Override
    public int getNumActive() throws UnsupportedOperationException {
        return objectPool.getNumActive();
    }

    @Override
    public void clear() throws Exception, UnsupportedOperationException {
        objectPool.clear();
    }

    @Override
    public void close() throws Exception {
        objectPool.close();
    }

    @Override
    public void setFactory(PoolableObjectFactory poolableObjectFactory) throws IllegalStateException, UnsupportedOperationException {
        objectPool.setFactory(poolableObjectFactory);
    }

}
